import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    if (response.data.success === false) {
      ElMessage.error(response.data.message || '操作失败')
      return Promise.reject(new Error(response.data.message || '操作失败'))
    }
    return response
  },
  error => {
    console.error('请求错误:', error.response)
    let message = '请求失败'
    if (error.response) {
      if (error.response.data && error.response.data.message) {
        message = error.response.data.message
      } else if (error.response.status === 400) {
        message = '请求参数错误'
      } else if (error.response.status === 401) {
        message = '未授权，请重新登录'
        // 清除 token 并跳转到登录页
        localStorage.removeItem('token')
        window.location.href = '/login'
      }
    }
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default request 